package org.checkboo.hopefullyengine.loaders;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.checkboo.hopefullyengine.sceneelements.BaseObject;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public class LoaderOgre {
	
	public static BaseObject loadFile(File modelFile){
		try{
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			FileInputStream fis = new FileInputStream(modelFile);
			
			OgreMeshHandler myOgreMeshHandler = new OgreMeshHandler();
			xr.setContentHandler(myOgreMeshHandler);
			xr.parse(new InputSource(fis));
			
			BaseObject model = new BaseObject();
			model.setVertices(myOgreMeshHandler.getVertices());
			model.setIndices(myOgreMeshHandler.getIndices());
			model.setVertexNormals(myOgreMeshHandler.getNormals());
			model.setTexCoords(myOgreMeshHandler.getTexCoords());
			model.setBoneAssignements(myOgreMeshHandler.getBoneAssings());
			
			String path = modelFile.getPath().substring(0, modelFile.getPath().lastIndexOf("/")+1);
			path += myOgreMeshHandler.getSkeletonXML()+".xml";		
			myOgreMeshHandler = null;
			System.gc();
			
			fis = new FileInputStream(new File(path));
			
			OgreSkeletonHandler myOgreSkeletonHandler = new OgreSkeletonHandler();
			xr.setContentHandler(myOgreSkeletonHandler);
			xr.parse(new InputSource(fis));
			
			model.setSkeleton(myOgreSkeletonHandler.getSkeleton());
			
			return model;
		}
		catch(SAXException e){
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
}


